package com.rutas.java;

import java.util.ArrayList;

import android.app.Application;
import android.util.Log;


/*
 * Clase que extiende el contexto de la aplicacion para proporcionar un cache para el tiempo
 */
public class RutasGlobal extends Application {

	private class WeatherItem{
		public long key;
		public long timeStamp;
		public String jsonWeather;
		public WeatherItem(long k, long t, String j){
			key = k;
			timeStamp = t;
			jsonWeather = j;
		}
	}
	
	private ArrayList<WeatherItem> cacheWeather;
	
	public void initialize(){
		if (cacheWeather == null)
			cacheWeather = new ArrayList<WeatherItem>();
	}
	
	public void addElement(long k, String json){
		long time = System.currentTimeMillis();
		WeatherItem wi = new WeatherItem(k, time, json);
		cacheWeather.add(wi);
	}
	public String searchElement(long key){
		int tam = cacheWeather.size();
		Log.v("SearchElem", ""+tam);
		int i = 0;
		boolean encontrado = false;
		String result = null;
		while ((i < tam) && (!encontrado)){
			WeatherItem wi = cacheWeather.get(i);
			if (wi.key == key){
				long TimeAct = System.currentTimeMillis();
				if ((TimeAct - wi.timeStamp) < 3600000){	//1 hora
					result = wi.jsonWeather;
				}else{
					cacheWeather.remove(i);
					Log.v("SearchElement removed",""+cacheWeather.size());
				}
				encontrado = true;
			}else
				i++;
		}
		return result;
	}
	@Override
	public void onCreate(){
		initialize();
		super.onCreate();
		Log.v("OnCreate Buffer", "TRUE!");
	}
	
	@Override
	public void onLowMemory(){
		cacheWeather.clear();
		super.onLowMemory();
	}
}
